package com.zbkj.service.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.zbkj.common.constants.SysConfigConstants;
import com.zbkj.common.constants.UploadConstants;
import com.zbkj.common.enums.RoleEnum;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.brand.Brand;
import com.zbkj.common.model.page.PageDiy;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.page.PageDiyEditNameRequest;
import com.zbkj.common.response.page.PageDiyResponse;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.result.SystemConfigResultCode;
import com.zbkj.common.utils.SecurityUtil;
import com.zbkj.service.dao.page.PageDiyDao;
import com.zbkj.service.service.*;
import com.zbkj.service.util.BrandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author dazongzi
* @description PageDiyServiceImpl 接口实现
* @date 2023-05-16
*/
@Service
public class PageDiyServiceImpl extends ServiceImpl<PageDiyDao, PageDiy> implements PageDiyService {

    private static final Logger logger = LoggerFactory.getLogger(PageDiyServiceImpl.class);

    @Resource
    private PageDiyDao dao;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private  BrandService brandService;
    @Autowired
    private SystemAdminService adminService;
    @Autowired
    private UserService userService;


    /**
    * 列表
    * @author dazongzi
    * @since 2023-05-16
    * @return List<PageDiy>
    */
    @Override
    public List<PageDiy> getList(String name, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<PageDiy> lambdaQueryWrapper = Wrappers.lambdaQuery();
        // 列表查询时忽略掉value字段，以免影响查询速度
        lambdaQueryWrapper.select(PageDiy.class, i -> !i.getColumn().equals("value"));
        lambdaQueryWrapper.eq(PageDiy::getIsDefault, 0);
        if(ObjectUtil.isNotEmpty(name)){
            lambdaQueryWrapper.like(PageDiy::getName, URLUtil.decode(name));
        }
     /*   if (BrandUtil.isBrand()){
            lambdaQueryWrapper.eq(PageDiy::getBrandId, BrandUtil.getBrandId());
        }else{
            lambdaQueryWrapper.eq(PageDiy::getBrandId, 0);
        }*/
        lambdaQueryWrapper.orderByDesc(PageDiy::getAddTime);
        List<PageDiy> pageDiys = dao.selectList(lambdaQueryWrapper);
        if(pageParamRequest.getPage() == 1){
            pageDiys.add(0, getDiyPageHome(Boolean.FALSE));
        }
        return pageDiys;
    }

    @Override
    public List<PageDiy> getListBrand(String name, PageParamRequest pageParamRequest, HttpServletRequest request) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<PageDiy> lambdaQueryWrapper = Wrappers.lambdaQuery();
        // 列表查询时忽略掉value字段，以免影响查询速度
        lambdaQueryWrapper.select(PageDiy.class, i -> !i.getColumn().equals("value"));
        lambdaQueryWrapper.eq(PageDiy::getIsDefault, 0);
        if(ObjectUtil.isNotEmpty(name)){
            lambdaQueryWrapper.like(PageDiy::getName, URLUtil.decode(name));
        }
        Integer brandId = BrandUtil.getBrandIdByUrl(request);
        lambdaQueryWrapper.eq(PageDiy::getBrandId, brandId);
     /*   if (BrandUtil.isBrand()){

        }else{
            lambdaQueryWrapper.eq(PageDiy::getBrandId, 0);
        }*/
        lambdaQueryWrapper.orderByDesc(PageDiy::getAddTime);
        List<PageDiy> pageDiys = dao.selectList(lambdaQueryWrapper);
        if(pageParamRequest.getPage() == 1){
            pageDiys.add(0, getDiyPageHome(Boolean.FALSE));
        }
        return pageDiys;
    }

    /**
     * 保存diy
     *
     * @param pageDiy diy数据
     */
    @Override
    public PageDiy savePageDiy(PageDiy pageDiy) {
        String adminApiPath = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_API_URL);
        if (StrUtil.isBlank(adminApiPath)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "应用设置中 微信小程序数据配置 或者 支付回调地址以及网站地址 配置不全");
        }

        // 检查diy模版名称唯一
        checkPageDiyNameUnique(pageDiy.getName(), null);
        DocumentContext jsonContext = JsonPath.parse(pageDiy.getValue());
        // 通配符去掉关键子 再存储
        jsonContext.delete("$..*[?(@ == '"+ adminApiPath +"')]");
        pageDiy.setValue(jsonContext.jsonString());
        /*if (BrandUtil.isBrand()){
            pageDiy.setBrandId(BrandUtil.getBrandId());
        }else{
            pageDiy.setBrandId(0);
        }*/
        save(pageDiy);
        return pageDiy;
    }
    @Override
    public PageDiy savePageDiyBrand(PageDiy pageDiy) {
        String adminApiPath = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_API_URL);
        if (StrUtil.isBlank(adminApiPath)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "应用设置中 微信小程序数据配置 或者 支付回调地址以及网站地址 配置不全");
        }

        // 检查diy模版名称唯一
        checkPageDiyNameUnique(pageDiy.getName(), null);
        DocumentContext jsonContext = JsonPath.parse(pageDiy.getValue());
        // 通配符去掉关键子 再存储
        jsonContext.delete("$..*[?(@ == '"+ adminApiPath +"')]");
        pageDiy.setValue(jsonContext.jsonString());
        pageDiy.setBrandId(BrandUtil.getBrandIdByUrl());
        save(pageDiy);
        return pageDiy;
    }

    /**
     * 更新diy
     *
     * @param pageDiy
     */
    @Override
    public Boolean editPageDiy(PageDiy pageDiy) {
        String adminApiPath = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_API_URL);
        if (StrUtil.isBlank(adminApiPath)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "应用设置中 微信小程序数据配置 或者 支付回调地址以及网站地址 配置不全");
        }
        // 检查diy模版名称唯一
        checkPageDiyNameUnique(pageDiy.getName(), pageDiy.getId());
        DocumentContext jsonContext = JsonPath.parse(pageDiy.getValue());
        // 通配符去掉关键子 再存储
        jsonContext.delete("$..*[?(@ == '"+ adminApiPath +"')]");
        pageDiy.setValue(jsonContext.jsonString());
        return dao.updateById(pageDiy)>0;
    }

    /**
     * 编辑diy名称
     *@param pageDiyEditNameRequest 待编辑名称对象
     */
    @Override
    public Boolean editPageDiyName(PageDiyEditNameRequest pageDiyEditNameRequest) {
        // 检查diy模版名称唯一
        checkPageDiyNameUnique(pageDiyEditNameRequest.getName(), pageDiyEditNameRequest.getId());

        PageDiy pageDiyForUpdate = new PageDiy();
        pageDiyForUpdate.setId(pageDiyEditNameRequest.getId());
        pageDiyForUpdate.setName(pageDiyEditNameRequest.getName());
        return dao.updateById(pageDiyForUpdate) > 0;
    }

    /**
     * 设置DIY首页模版
     * isDefault =1 是平台首页 2=商户 diy后期商户再处理
     *
     * @param diyId 被设置为首页的diy模版id
     * @return 设置结果
     */
    @Override
    public Boolean setDiyPageHome(Integer diyId) {
        PageDiy pageDiy = dao.selectById(diyId);
        if(ObjectUtil.isNull(pageDiy)) throw new AppException(CommonResultCode.VALIDATE_FAILED, "当前DIY模版不存在");

        // 取消现有的首页设置，如果存在的话
        LambdaQueryWrapper<PageDiy> queryWaiteResetDefaultTemp = Wrappers.lambdaQuery();
        queryWaiteResetDefaultTemp.eq(PageDiy::getIsDefault, 1);
        queryWaiteResetDefaultTemp.eq(PageDiy::getBrandId, BrandUtil.getBrandIdByUrl());
        List<PageDiy> currentWaitResetPageHome = dao.selectList(queryWaiteResetDefaultTemp);
        List<PageDiy> currentTempByReset = currentWaitResetPageHome.stream().map(homeTemp -> homeTemp.setIsDefault(0)).collect(Collectors.toList());
        saveOrUpdateBatch(currentTempByReset);

        // 设置当前diy数据为商城首页
        pageDiy.setIsDefault(1);
        return dao.updateById(pageDiy) > 0;
    }

    /**
     * 获取DIY首页模版Id
     *@param isLoadValue 是否加载value详情数据
     * @return 首页模版ID
     */
    @Override
    public PageDiy getDiyPageHome(Boolean isLoadValue) {
        SystemAdmin admin = SecurityUtil.getLoginUserVo().getUser();
        LambdaQueryWrapper<PageDiy> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PageDiy::getIsDefault, 1);
        // 如果当前用户是平台超管，则加载平台首页模板
        if (Objects.equals(admin.getType(), RoleEnum.SUPER_ADMIN.getValue())) {
            queryWrapper.eq(PageDiy::getBrandId, 0);
        } else {
            queryWrapper.eq(PageDiy::getBrandId, admin.getId());
        }
        if(Boolean.FALSE == isLoadValue){
            queryWrapper.select(PageDiy.class, i -> !i.getColumn().equals("value"));
        }
        List<PageDiy> currentWaitResetPageHome = dao.selectList(queryWrapper);
        if(ObjectUtil.isNull(currentWaitResetPageHome) || currentWaitResetPageHome.size() != 1){
            throw new AppException("首页模版设置不正确！");
        }

        PageDiy pageDiy = currentWaitResetPageHome.get(0);
        if(Boolean.TRUE == isLoadValue){
            String modifiedJsonString = getModifiedJsonString(pageDiy.getValue());
            pageDiy.setValue(modifiedJsonString);
        }
        return pageDiy;
    }


    /**
     * 针对Admin
     * 根据id加载diy模版配置
     *
     * @param id 对应的模版id
     *           描述：
     *           id=0加载商城首页的，也就是setDiyPageHome后的数据，平台端会默认设置已经有首页的数据，也会预制
     *           id>1时加载对应的模版即可
     */
    @Override
    public PageDiy getDiyPageByPageIdForAdmin(Integer id) {
        PageDiy pageDiy = null;
        if(0 == id){
            LambdaQueryWrapper<PageDiy> getHomeDefault = Wrappers.lambdaQuery();
            getHomeDefault.eq(PageDiy::getIsDefault, 1);
            pageDiy = getOne(getHomeDefault);
        }else{
            pageDiy = getById(id);
        }

        if(ObjectUtil.isNull(pageDiy)) throw new AppException(SystemConfigResultCode.PAGE_DIY_NOT_EXIST);

        String modifiedJsonString = getModifiedJsonString(pageDiy.getValue());
        pageDiy.setValue(modifiedJsonString);
        return pageDiy;
    }

    @Override
    public PageDiy getDiyPageByPageIdForAdminBrand(Integer id) {
        PageDiy pageDiy = null;
        if(0 == id){
            LambdaQueryWrapper<PageDiy> getHomeDefault = Wrappers.lambdaQuery();
            getHomeDefault.eq(PageDiy::getIsDefault, 1);
            getHomeDefault.eq(PageDiy::getBrandId, BrandUtil.getBrandIdByUrl());
            pageDiy = getOne(getHomeDefault);
        }else{
            pageDiy = getById(id);
        }

        if(ObjectUtil.isNull(pageDiy)) throw new AppException(SystemConfigResultCode.PAGE_DIY_NOT_EXIST);

        String modifiedJsonString = getModifiedJsonStringBrand(pageDiy.getValue());
        pageDiy.setValue(modifiedJsonString);
        return pageDiy;
    }

    @Override
    public PageDiy getFirst() {
        LambdaQueryWrapper<PageDiy> getHomeDefault = Wrappers.lambdaQuery();
        getHomeDefault.orderByAsc(PageDiy::getId);
        getHomeDefault.last("limit 1");
        return getOne(getHomeDefault);
    }

    private String getModifiedJsonStringBrand(String jsonString) {
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
        modifyJson(jsonObject, "https://xtwy-gns.oss-cn-beijing.aliyuncs.com/");
        return gson.toJson(jsonObject);
    }

    private void modifyJson(JsonObject jsonObject, String prefix) {
        for (String key : jsonObject.keySet()) {
            JsonElement value = jsonObject.get(key);
            if (value.isJsonObject()) {
                modifyJson(value.getAsJsonObject(), prefix);
            } else if (value.isJsonArray()) {
                for (JsonElement element : value.getAsJsonArray()) {
                    if (element.isJsonObject()) {
                        modifyJson(element.getAsJsonObject(), prefix);
                    }
                }
            } else if (value.isJsonPrimitive() && value.getAsString().startsWith(prefix)) {
                jsonObject.addProperty(key, removePrefix(value.getAsString(), prefix));
            }
        }
    }

    private String removePrefix(String url, String prefix) {
        if (url != null && url.startsWith(prefix)) {
            return url.substring(prefix.length());
        }
        return url;
    }

    /**
     * 根据id加载diy模版配置
     *
     * @param id 对应的模版id
     *           描述：
     *           id=0加载商城首页的，也就是setDiyPageHome后的数据，平台端会默认设置已经有首页的数据，也会预制
     *           id>1时加载对应的模版即可
     */

    @Override
    public PageDiyResponse getDiyPageByPageIdForFront(String id, Integer pageDiyId) {
        if ((id.equals(BrandUtil.ZFB_URI) || id.equals(BrandUtil.ZFB_URI_TEST)) && (ObjectUtil.isNull(pageDiyId) || pageDiyId <= 0) ) {
            PageDiy pageDiy;
            LambdaQueryWrapper<PageDiy> getHomeDefault = Wrappers.lambdaQuery();
            getHomeDefault.eq(PageDiy::getIsDefault, 1);
            getHomeDefault.eq(PageDiy::getBrandId, 0);
            PageDiy pageDiy1 = dao.selectOne(getHomeDefault);
            pageDiy = getById(pageDiy1.getId());

            if (ObjectUtil.isNull(pageDiy)) throw new AppException(SystemConfigResultCode.PAGE_DIY_NOT_EXIST);
            // 优化front比必要的字段 提高diy组件渲染效率
            DocumentContext jsonContext = JsonPath.parse(pageDiy.getValue());
            jsonContext.delete("$..*[?(@.name == 'goodList')].itemStyle.list");
            jsonContext.delete("$..*[?(@.name == 'goodList')].tabConfig.list");
            jsonContext.delete("$..*[?(@.name == 'goodList')].typeConfig.list");
//        jsonContext.delete("$..*[?(@.name == 'goodList')].selectConfig");
            jsonContext.delete("$..*[?(@.name == 'goodList')].goodsSort.list");
            jsonContext.delete("$..*[?(@.name == 'goodList')].goodsList.list[*].attrValue");
            jsonContext.delete("$..*[?(@.name == 'homeTab')].activeValueBrand");
            jsonContext.delete("$..*[?(@.name == 'homeTab')].goodsList");
            jsonContext.delete("$..*[?(@.name == 'homeTab')].selectConfig");
            jsonContext.delete("$..*[?(@.name == 'homeTab')].productList..*.goods[*].attrValue");

            PageDiyResponse response = new PageDiyResponse();
            BeanUtils.copyProperties(pageDiy, response);
//            String modifiedJsonString = getModifiedJsonString(jsonContext.jsonString());
            String modifiedJsonString = getModifiedJsonStringBrand(pageDiy.getValue());
            response.setValue(JSON.parseObject(modifiedJsonString));
            return response;
        }

        PageDiy pageDiy;
        if (pageDiyId == null || pageDiyId == 0) {
            SystemAdmin brandAdmin = getBrandAdmin(id);
            LambdaQueryWrapper<PageDiy> getHomeDefault = Wrappers.lambdaQuery();
            getHomeDefault.eq(PageDiy::getIsDefault, 1);
            getHomeDefault.eq(PageDiy::getBrandId,brandAdmin.getId());
            PageDiy pageDiy1 = dao.selectOne(getHomeDefault);
            pageDiy = getById(pageDiy1.getId());
        } else {
            pageDiy = getById(pageDiyId);
        }

        if(ObjectUtil.isNull(pageDiy)) throw new AppException(SystemConfigResultCode.PAGE_DIY_NOT_EXIST);

        // 优化front比必要的字段 提高diy组件渲染效率
        DocumentContext jsonContext = JsonPath.parse(pageDiy.getValue());
        jsonContext.delete("$..*[?(@.name == 'goodList')].itemStyle.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].tabConfig.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].typeConfig.list");
//        jsonContext.delete("$..*[?(@.name == 'goodList')].selectConfig");
        jsonContext.delete("$..*[?(@.name == 'goodList')].goodsSort.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].goodsList.list[*].attrValue");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].activeValueBrand");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].goodsList");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].selectConfig");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].productList..*.goods[*].attrValue");

        PageDiyResponse response = new PageDiyResponse();
        BeanUtils.copyProperties(pageDiy, response);
//        String modifiedJsonString = getModifiedJsonString(jsonContext.jsonString());
        String modifiedJsonString = getModifiedJsonStringBrand(pageDiy.getValue());
        JSONObject jsonObject= JSON.parseObject(modifiedJsonString);

        //2025-11-18 关注的店铺的商品排在前面
        if (jsonObject!=null){
            getMerchantCollect( jsonObject);
        }

        response.setValue(jsonObject);
        return response;
    }

    /**
     * 关注的店铺的商品排在前面
     * @param jsonObject
     */
    public void getMerchantCollect(JSONObject jsonObject) {
        try {
            Integer uid = userService.getUserIdException();
            if (jsonObject!=null && uid!=null){
                List<Integer> ids = dao.getMerchantCollect(uid);
               if (ids!=null && ids.size()>0){
                   JSONObject jsonObject1 = findNestedJSONObject( jsonObject, "tabItemConfig");
                   if (jsonObject1!=null){
                       JSONArray jsonArray = jsonObject1.getJSONArray("list");
                       if (jsonArray!=null && jsonArray.size()>0){
                           JSONObject jsonOb  = jsonArray.getJSONObject(0);
                           if (jsonOb!=null){
                               JSONObject activeList = jsonOb.getJSONObject("activeList");
                               if (activeList!=null){

                                   JSONArray goods = activeList.getJSONArray("goods");
                                   // 重新排序goods数组，将匹配id的对象排到前面
                                   if (goods != null && goods.size() > 0) {
                                       sortGoodsArrayByIds(goods, ids);
                                   }
                               }

                           }
                       }

                   }
               }
            }
        } catch (Exception e) {
            logger.error("处理关注店铺商品排序时发生异常", e);
        }
    }
    /**
     * 根据指定ID列表重新排序goods数组，将匹配的对象排到前面
     * @param goodsArray 原始goods数组
     * @param targetIds 需要优先排列的ID列表
     */
    private void sortGoodsArrayByIds(JSONArray goodsArray, List<Integer> targetIds) {
        List<JSONObject> matchedItems = new ArrayList<>();
        List<JSONObject> unmatchedItems = new ArrayList<>();

        // 分离匹配和不匹配的项
        for (int i = 0; i < goodsArray.size(); i++) {
            JSONObject item = goodsArray.getJSONObject(i);
            Integer id = item.getInteger("id");

            if (id != null && targetIds.contains(id)) {
                matchedItems.add(item);
            } else {
                unmatchedItems.add(item);
            }
        }

        // 清空原数组并重新添加，匹配的项在前
        goodsArray.clear();
        for (JSONObject item : matchedItems) {
            goodsArray.add(item);
        }
        for (JSONObject item : unmatchedItems) {
            goodsArray.add(item);
        }
    }
    /**
     * 递归查找 JSONObject 中指定名称的属性
     * @param jsonObject 要搜索的 JSONObject
     * @param keyName 要查找的属性名
     * @return 找到的 JSONObject 或 null
     */

    public JSONObject findNestedJSONObject(JSONObject jsonObject, String keyName) {
        if (jsonObject.containsKey(keyName)) {
            return jsonObject.getJSONObject(keyName);
        }

        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                JSONObject result = findNestedJSONObject((JSONObject) value, keyName);
                if (result != null) {
                    return result;
                }
            } else if (value instanceof JSONArray) {
                JSONArray array = (JSONArray) value;
                for (int i = 0; i < array.size(); i++) {
                    Object item = array.get(i);
                    if (item instanceof JSONObject) {
                        JSONObject result = findNestedJSONObject((JSONObject) item, keyName);
                        if (result != null) {
                            return result;
                        }
                    }
                }
            }
        }

        return null;
    }

    public static String extractDomain(String url) {
        // 找到第一个 "//" 的位置
        int firstSlashIndex = url.indexOf("//") + 2;

        // 找到第二个 "/" 的位置
        int secondSlashIndex = url.indexOf('/', firstSlashIndex);

        // 如果没有找到第二个 "/"，则截取到字符串末尾
        if (secondSlashIndex == -1) {
            return url.substring(firstSlashIndex);
        }

        // 截取从第一个 "//" 后面到第二个 "/" 之间的字符串
        return url.substring(firstSlashIndex, secondSlashIndex);
    }
    public   SystemAdmin getBrandAdmin(String uriDomain){
//        String url = extractDomain(uriDomain);
        Brand one = brandService.getOne(new LambdaQueryWrapper<Brand>().eq(Brand::getShareUrl, uriDomain));
        SystemAdmin admin = adminService.getOne(new LambdaQueryWrapper<SystemAdmin>().eq(SystemAdmin::getBrandId, one.getId()));
        return admin;
    }
    @Override
    public PageDiyResponse getDiyPageByPageIdForFrontBrand(String url) {
        SystemAdmin brandAdmin = getBrandAdmin(url);
        PageDiy pageDiy;
        LambdaQueryWrapper<PageDiy> getHomeDefault = Wrappers.lambdaQuery();
        getHomeDefault.eq(PageDiy::getIsDefault, 1);
        getHomeDefault.eq(PageDiy::getBrandId,brandAdmin.getId());
        PageDiy one = getOne(getHomeDefault);
        pageDiy = getById(one.getId());

        logger.info("pageDiy1:"+pageDiy);
       /* pageDiy = getById(pageDiy.getId());
        logger.info("pageDiy2:"+pageDiy);*/
        if(ObjectUtil.isNull(pageDiy)) throw new AppException(SystemConfigResultCode.PAGE_DIY_NOT_EXIST);


        // 优化front比必要的字段 提高diy组件渲染效率
        DocumentContext jsonContext = JsonPath.parse(pageDiy.getValue());
        jsonContext.delete("$..*[?(@.name == 'goodList')].itemStyle.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].tabConfig.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].typeConfig.list");
//        jsonContext.delete("$..*[?(@.name == 'goodList')].selectConfig");
        jsonContext.delete("$..*[?(@.name == 'goodList')].goodsSort.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].goodsList.list[*].attrValue");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].activeValueBrand");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].goodsList");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].selectConfig");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].productList..*.goods[*].attrValue");

        PageDiyResponse response = new PageDiyResponse();
        BeanUtils.copyProperties(pageDiy, response);
        String modifiedJsonString = getModifiedJsonString(jsonContext.jsonString());
        response.setValue(JSON.parseObject(modifiedJsonString));
        return response;
    }


    /**
     * 检查diy模版名称唯一
     * @param pageDiyName 当前要检查的模版名称
     * @param id 更新时的 diy id
     */
    private void checkPageDiyNameUnique(String pageDiyName, Integer id) {
        Integer brandId = BrandUtil.getBrandIdByUrl();
        LambdaQueryWrapper<PageDiy> pageDiyLambdaQueryWrapper = Wrappers.lambdaQuery();
        pageDiyLambdaQueryWrapper.eq(PageDiy::getName, pageDiyName);
        if(ObjectUtil.isNotNull(id)){
            pageDiyLambdaQueryWrapper.ne(PageDiy::getId, id);
        }
        if (ObjectUtil.isNotNull(brandId) && brandId > 0) {
            pageDiyLambdaQueryWrapper.eq(PageDiy::getBrandId, brandId);
        }
        List<PageDiy> pageDiyNameExist = dao.selectList(pageDiyLambdaQueryWrapper);
        if(ObjectUtil.isNotNull(pageDiyNameExist) && !pageDiyNameExist.isEmpty()){
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "当前模版名称已经存在，请修改后再保存！");
        }
    }

////////////////////////////////// 内部处理json配置中的素材地址方法 START

    /**
     * 调用diy配置数据后结合本地配置，传递给递归方法替换
     * @param diyValue 当前待操作的diy对象，其实仅仅用到了value
     * @return 替换后的json对象
     */
    private String getModifiedJsonString(String diyValue) {
        // 使用 Gson 解析 JSON 数据
        Gson gson = new Gson();
        JsonElement jsonElement = gson.fromJson(diyValue, JsonElement.class);

        // 替换指定前缀的键
        String adminApiPath = UploadConstants.UPLOAD_FILE_KEYWORD;
        String newPrefix = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_LOCAL_UPLOAD_URL);
        JsonElement modifiedJsonElement = replaceJsonValue(jsonElement, adminApiPath, newPrefix);
//        JsonElement modifiedJsonElement = replaceJsonValue(jsonElement, adminApiPath);

        // 将修改后的 JSON 数据转换回字符串
        return  gson.toJson(modifiedJsonElement);
    }

/*    private String getModifiedJsonStringBrand(String diyValue) {
        // 使用 Gson 解析 JSON 数据
        Gson gson = new Gson();
        JsonElement jsonElement = gson.fromJson(diyValue, JsonElement.class);

        // 替换指定前缀的键
        String adminApiPath = UploadConstants.UPLOAD_FILE_KEYWORD;
        String newPrefix = systemConfigService.getValueByKeyBrand(SysConfigConstants.CONFIG_LOCAL_UPLOAD_URL);
        JsonElement modifiedJsonElement = replaceJsonValue(jsonElement, adminApiPath);

        // 将修改后的 JSON 数据转换回字符串
        return  gson.toJson(modifiedJsonElement);
    }*/

    /**
     * 根据系统关键字匹配素材前缀，匹配后追加系统中对应的素材前缀
     * @param jsonElement 当前操作的json对象
     * @param keyword 匹配的关键字
     * @param newValue 需要追加的前缀
     * @return 操作后的正确json数据
     */
    private JsonElement replaceJsonValue(JsonElement jsonElement, String keyword, String newValue) {
        if (jsonElement.isJsonObject()) {
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            JsonObject newJsonObject = new JsonObject();
            for (String key : jsonObject.keySet()) {
                JsonElement value = jsonObject.get(key);
                if (value.isJsonPrimitive() && value.getAsString().startsWith(keyword)) {
                    newJsonObject.addProperty(key, newValue + "/" + value.getAsString());
                } else {
                    newJsonObject.add(key, replaceJsonValue(value, keyword, newValue)); // 递归处理子元素
                }
            }
            return newJsonObject;
        } else if (jsonElement.isJsonArray()) {
            // 如果数组元素也可能含有关键字，可以按需处理
            JsonArray jsonArray = jsonElement.getAsJsonArray();
            JsonArray newJsonArray = new JsonArray();
            for (JsonElement element : jsonArray) {
                newJsonArray.add(replaceJsonValue(element, keyword, newValue)); // 递归处理数组元素
            }
            return newJsonArray;
        } else {
            return jsonElement;
        }
    }

    /**
     * 根据系统关键字匹配素材前缀，匹配后追加系统中对应的素材前缀
     * @param jsonElement 当前操作的json对象
     * @param keyword 匹配的关键字
     * @param newValue 需要追加的前缀
     * @return 操作后的正确json数据
     */
    private JsonElement replaceJsonValue(JsonElement jsonElement, String keyword) {
        if (jsonElement.isJsonObject()) {
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            JsonObject newJsonObject = new JsonObject();
            for (String key : jsonObject.keySet()) {
                JsonElement value = jsonObject.get(key);
                if (value.isJsonPrimitive() && value.getAsString().startsWith(keyword)) {
                    newJsonObject.addProperty(key, value.getAsString()); // 直接使用原始值
                } else {
                    newJsonObject.add(key, replaceJsonValue(value, keyword)); // 递归处理子元素
                }
            }
            return newJsonObject;
        } else if (jsonElement.isJsonArray()) {
            // 如果数组元素也可能含有关键字，可以按需处理
            JsonArray jsonArray = jsonElement.getAsJsonArray();
            JsonArray newJsonArray = new JsonArray();
            for (JsonElement element : jsonArray) {
                newJsonArray.add(replaceJsonValue(element, keyword)); // 递归处理数组元素
            }
            return newJsonArray;
        } else {
            return jsonElement;
        }
    }


    ////////////////////////////////// 内部处理json配置中的素材地址方法 END

    /**
     * 根据id加载diy模版配置
     *
     * @param id 对应的模版id
     *           描述：
     *           id=0加载商城首页的，也就是setDiyPageHome后的数据，平台端会默认设置已经有首页的数据，也会预制
     *           id>1时加载对应的模版即可
     */

    @Override
    public PageDiyResponse getDiyPageByPageIdForFront(String id) {
        SystemAdmin brandAdmin = getBrandAdmin(id);
        PageDiy pageDiy;
        LambdaQueryWrapper<PageDiy> getHomeDefault = Wrappers.lambdaQuery();
        getHomeDefault.eq(PageDiy::getIsDefault, 1);
        getHomeDefault.eq(PageDiy::getBrandId,brandAdmin.getId());
        PageDiy pageDiy1 = dao.selectOne(getHomeDefault);
        pageDiy = getById(pageDiy1.getId());

        if(ObjectUtil.isNull(pageDiy)) throw new AppException(SystemConfigResultCode.PAGE_DIY_NOT_EXIST);


        // 优化front比必要的字段 提高diy组件渲染效率
        DocumentContext jsonContext = JsonPath.parse(pageDiy.getValue());
        jsonContext.delete("$..*[?(@.name == 'goodList')].itemStyle.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].tabConfig.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].typeConfig.list");
//        jsonContext.delete("$..*[?(@.name == 'goodList')].selectConfig");
        jsonContext.delete("$..*[?(@.name == 'goodList')].goodsSort.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].goodsList.list[*].attrValue");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].activeValueBrand");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].goodsList");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].selectConfig");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].productList..*.goods[*].attrValue");

        PageDiyResponse response = new PageDiyResponse();
        BeanUtils.copyProperties(pageDiy, response);
//        String modifiedJsonString = getModifiedJsonString(jsonContext.jsonString());
        String modifiedJsonString = getModifiedJsonStringBrand(pageDiy.getValue());
        response.setValue(JSON.parseObject(modifiedJsonString));
        return response;
    }

    @Override
    public PageDiyResponse getDiyPageByPageIdForFront(Integer id,String url) {
        SystemAdmin brandAdmin = getBrandAdmin(url);
        PageDiy pageDiy;
        if(brandAdmin==null){
            if(0 == id){
                LambdaQueryWrapper<PageDiy> getHomeDefault = Wrappers.lambdaQuery();
                getHomeDefault.eq(PageDiy::getIsDefault, 1);
                pageDiy = getOne(getHomeDefault);
            }else {
                pageDiy = getById(id);
            }
        }else{
            LambdaQueryWrapper<PageDiy> getHomeDefault = Wrappers.lambdaQuery();
            getHomeDefault.eq(PageDiy::getIsDefault, 1);
            getHomeDefault.eq(PageDiy::getBrandId,brandAdmin.getId());
            pageDiy = getOne(getHomeDefault);
        }

        if(ObjectUtil.isNull(pageDiy)) throw new AppException(SystemConfigResultCode.PAGE_DIY_NOT_EXIST);


        // 优化front比必要的字段 提高diy组件渲染效率
        DocumentContext jsonContext = JsonPath.parse(pageDiy.getValue());
        jsonContext.delete("$..*[?(@.name == 'goodList')].itemStyle.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].tabConfig.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].typeConfig.list");
//        jsonContext.delete("$..*[?(@.name == 'goodList')].selectConfig");
        jsonContext.delete("$..*[?(@.name == 'goodList')].goodsSort.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].goodsList.list[*].attrValue");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].activeValueBrand");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].goodsList");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].selectConfig");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].productList..*.goods[*].attrValue");

        PageDiyResponse response = new PageDiyResponse();
        BeanUtils.copyProperties(pageDiy, response);
        String modifiedJsonString = getModifiedJsonString(jsonContext.jsonString());
        response.setValue(JSON.parseObject(modifiedJsonString));
        return response;
    }

}

